"use strict";
const pkgDir = require("pkg-dir").sync;
const path = require("path");
const { isObject } = require("@liusion-cli-dev/utils");
const formatPath = require("@liusion-cli-dev/format-path");
const { getDefaultRegistry } = require("@liusion-cli-dev/get-npm-info");
const npminstall = require("npminstall");

class Package {
  constructor(options) {
    if (!options) {
      throw new Error("Package类的option不能为空");
    }
    if (!isObject(options)) {
      throw new Error("Package类的option必须为对象");
    }
    console.log("Package constructor");
    // package的目标路径
    this.targetPath = options.targetPath;
    // package的缓存路径
    this.storeDir = options.storeDir;
    this.packageName = options.packageName;
    this.packageVersion = options.packageVersion;
  }

  exists() {}

  install() {
    npminstall({
      root: this.targetPath,
      storeDir: this.storeDir,
      registry: getDefaultRegistry(),
      pkgs: [{ name: this.packageName, version: this.packageVersion }],
    });
  }

  update() {}

  getRootFilePath() {
    const dir = pkgDir(this.targetPath);
    if (dir) {
      const pkgFile = require(path.join(dir, "package.json"));
      console.log("pkgFile", pkgFile);
      if (pkgFile && pkgFile.main) {
        return formatPath(path.resolve(dir, pkgFile.main));
      }
    }
    return null;
  }
}

module.exports = Package;
